﻿using System;
using System.Linq;
using System.Collections.Generic;
using VIT.DataAccessLayer;
using VIT.Entity;
using VIT.DataHelper.LinqHelper.Infrastructure;

namespace VIT.BusinessLogicLayer
{
    public class SEOBLL : BLLBase
    {
        private readonly SEODAL _SEODAL;

        #region Constructor

        public SEOBLL()
            : base()
        {
        }

        public SEOBLL(UnitOfWork unitOfWork)
            : base(unitOfWork)
        {
        }

        public SEOBLL(string connectionString)
            : base(connectionString)
        {
            _SEODAL = new SEODAL(DatabaseFactory);
        }
        #endregion

        #region SEO
        public List<SEO> SEOGetAll(out int TotalPage, int Skip = 0, int Take = 0)
        {
            var lst = _SEODAL.GetAll();
            TotalPage = lst.Count();
            lst = lst.OrderByDescending(o => o.CreateDate);
            if (Skip > 0) lst = lst.Skip(Skip);
            if (Take > 0) lst = lst.Take(Take);
            return lst.ToList();
        }
        public SEO SEOGetById(string URL)
        {
            return _SEODAL.Get(o => o.SEOURL == URL || o.URL == URL);
        }
        public bool SEODeletes(string[] Ids)
        {
            try
            {
                foreach (var url in Ids)
                {
                    var grp = _SEODAL.Get(o => o.SEOURL == url);
                    if (grp != null)
                    {
                        _SEODAL.Delete(grp);
                    }
                }
                SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public SEO SEOSave(SEO seoLink, string UserModify)
        {
            try
            {
                var seo = _SEODAL.Get(o => o.SEOURL == seoLink.SEOURL);
                if (seo == null) //thêm
                {
                    seo = new SEO();
                    seo.CreateByUser = UserModify;
                    seo.CreateDate = DateTime.Now;
                    _SEODAL.Add(seo);
                }
                else // sửa
                {
                    seo.ModifyDate = DateTime.Now;
                    seo.ModifyByUser = UserModify;
                    _SEODAL.Update(seo);
                }

                seo.SEOURL = seoLink.SEOURL;
                seo.Title = seoLink.Title;
                seo.URL = seoLink.URL;
                seo.MetaKeyWork = seoLink.MetaKeyWork;
                seo.MetaDescription = seoLink.MetaDescription;

                SaveChanges();
                return seo;
            }
            catch
            {
                return null;
            }
        }
        #endregion
    }
}